import React, { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import styles from "./index.module.css";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import {
  Radio,
  Select,
  DatePicker,
  Table,
  Space,
  Image,
  Form,
  Button,
  Card,
  Tag,
  Modal,
  message,
} from "antd";
import { getContent, getChannels, deleteContent } from "@requests/content";
import defaultImg from "@image/placeholder.png";

const Content = () => {
  const navigate = useNavigate();

  const params = useRef({
    page: 1,
    per_page: 10,
    channel_id: undefined,
    status: undefined,
    begin_pubdate: undefined,
    end_pubdate: undefined,
  });
  const total_count = useRef(0);
  //获取文章数据
  const [list, setList] = useState([]);
  const getContentList = async (val: object) => {
    console.log("val", val);

    const res = await getContent(val);
    setList(res.data.results);
    total_count.current = res.data.total_count;
  };
  // 频道
  const [channels, setChannels] = useState([]);
  const getChannelsList = async () => {
    const res = await getChannels();
    setChannels(res.data.channels);
  };
  useEffect(() => {
    getContentList(params.current);
    getChannelsList();
  }, []);

  const onFinish = (val: any) => {
    console.log(val);
    params.current.status = val.status;
    params.current.channel_id = val.channel_id;
    params.current.page = 1;
    getContentList(params.current);
  };
  const onPageChange = (page: number, pageSize: number) => {
    params.current.page = page;
    params.current.per_page = pageSize;
    getContentList(params.current);
  };
  //删除
  const delOne = (id: any) => {
    console.log(id);
    Modal.confirm({
      title: "您是否确认删除该文章？",
      cancelText: "取消",
      okText: "确认",
      onOk: async () => {
        await deleteContent(id);
        getContentList(params.current);
        message.success("删除成功");
      },
    });
  };

  const statusLabel = [
    { text: "草稿", color: "default" },
    { text: "待审核", color: "blue" },
    { text: "审核通过", color: "green" },
    { text: "审核拒绝", color: "red" },
  ];
  const columns = [
    {
      title: "封面",
      dataIndex: "cover",
      key: "cover",
      render: (cover: any) => (
        <Image
          // 使用可选链操作符（?.）检查cover对象是否存在。
          // 如果cover对象存在，使用可选链操作符检查images数组是否存在。
          // 如果images数组存在，使用数组索引[0]获取第一个元素。
          // 如果images数组不存在或为空，使用defaultImg作为src属性的值。
          src={cover?.images?.[0] || defaultImg}
          style={{ objectFit: "cover" }}
          width={200}
          height={120}
        />
      ),
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: any) => {
        const info = statusLabel[status];
        return <Tag color={info.color}>{info.text}</Tag>;
      },
    },
    {
      title: "发布时间",
      dataIndex: "pubdate",
      key: "pubdate",
    },
    {
      title: "阅读数",
      dataIndex: "read_count",
      key: "read_count",
    },
    {
      title: "评论数",
      dataIndex: "comment_count",
      key: "comment_count",
    },
    {
      title: "点赞数",
      dataIndex: "like_count",
      key: "like_count",
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => navigate(`/home/article?id=${record.id}`)}
          />
          <Button
            type="link"
            onClick={() => delOne(record.id)}
            icon={<DeleteOutlined />}
          />
        </Space>
      ),
    },
  ];
  return (
    <div className={styles.root}>
      {/* 表单 */}
      <Form onFinish={onFinish}>
        <Form.Item label="状态：" name="status">
          <Radio.Group>
            <Radio value={undefined}>全部</Radio>
            <Radio value={0}>草稿</Radio>
            <Radio value={1}>待审核</Radio>
            <Radio value={2}>已通过</Radio>
            <Radio value={3}>已拒绝</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="频道：" name="channel_id">
          <Select
            style={{ width: 288 }}
            options={channels.map((province: any) => ({
              label: province.name,
              value: province.id,
            }))}
          ></Select>
        </Form.Item>
        <Form.Item label="日期：" name="dateArr">
          <DatePicker.RangePicker />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            筛选
          </Button>
        </Form.Item>
      </Form>
      <Card
        title={`根据筛选条件共查询到 100 条结果：`}
        style={{ marginTop: 24 }}
      >
        <Table
          columns={columns}
          dataSource={list}
          rowKey="id"
          pagination={{
            current: params.current.page,
            pageSize: params.current.per_page,
            total: total_count.current,
            onChange: onPageChange,
          }}
        ></Table>
      </Card>
    </div>
  );
};

export default Content;
